/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of JoinUs!.

JoinUs! is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

JoinUs! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with JoinUs!. If not, see <http://www.gnu.org/licenses/>. */
package br.ufes.cwtools.joinus.home.campaigns;

import java.io.StringReader;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import org.xml.sax.InputSource;

import br.ufes.cwtools.joinus.services.FileManagerDaemon;
import br.ufes.cwtools.joinus.util.DBHelper;
import br.ufes.cwtools.joinus.util.ServerCom;

import android.app.Dialog;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import br.ufes.cwtools.joinus.R;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;


public class CampDetails extends ListActivity implements Runnable
{
	protected LayoutInflater inflate; //ViewInflate inflate;
	Boolean validThread=new Boolean(false);
	ListView attach;
	ListView members;
	private SQLiteDatabase myBase;
	String campName, userName, id, desc;
	String creator, isPublic;
	long secondsToGo=60;
	long millis;
	String list[];
	Vector<Attachs> att;
	private Dialog d;
	Button download,upload,refresh;

	public void onCreate(Bundle icicle) 
	{
		super.onCreate(icicle);
		id = this.getIntent().getStringExtra("id");
		String xml2 = ServerCom.getCampMembers(Long.parseLong(id));
		Log.d("date",xml2);
		list = xml2.split(":");
		DBHelper database = new DBHelper();
		
		myBase = this.openOrCreateDatabase("homedb", MODE_PRIVATE, null);
		database.onCreate(myBase);	

		userName = this.getIntent().getStringExtra("user");

		if (id != null && userName != null) {

			Cursor query = myBase.query("activeCamp", null, "user='"
					+ userName + "' and id ='"+id+"'", null, null, null, null);

			query.moveToPosition(0);

			desc = query.getString(7);
			creator = query.getString(6);
			campName = query.getString(5);
			isPublic = query.getString(10);

			String date = query.getString(8);
			
			query.close();

			Log.d("date",date);

			String day = date.split(" ")[0];
			String hour = date.split(" ")[1];

			int second = Integer.parseInt(hour.split(":")[2]);
			int minute = Integer.parseInt(hour.split(":")[1]);
			int hour_value = Integer.parseInt(hour.split(":")[0]);
			int day_value = Integer.parseInt(day.split("-")[2]);
			int month = Integer.parseInt(day.split("-")[1]);
			int year = Integer.parseInt(day.split("-")[0]);

			Calendar c = Calendar.getInstance();
			c.set(Calendar.SECOND, second);
			c.set(Calendar.MINUTE, minute);
			c.set(Calendar.HOUR_OF_DAY, hour_value);
			c.set(Calendar.DAY_OF_MONTH, day_value);
			c.set(Calendar.MONTH, month-1);
			c.set(Calendar.YEAR, year);

			millis = c.getTimeInMillis();

			c = Calendar.getInstance();
			Log.d("now!",c.getTimeInMillis()+"");
			Log.d("camp!",millis+"");
			//	id="1";

			Log.d("campid",id);

			String xml = ServerCom.getAttachments(id);

			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xml));
			Attachs factory = new Attachs();
			att = factory.fromXml(is);
		}

		inflate = this.getLayoutInflater();  //inflate = this.getViewInflate();        
		ListView list = this.getListView();
		list.addFooterView(inflate.inflate(R.layout.campdet_foot, null));  //, null));

		View[] mDialogue = 
		{
				inflate.inflate(R.layout.campdet_main, null), //, null),
				inflate.inflate(R.layout.campdet_deta, null), //, null),
				inflate.inflate(R.layout.campdet_atta, null), //, null),
				inflate.inflate(R.layout.campdet_memb, null), //, null)
		};

		View[] mTitles = 
		{
				new TextView(this),
				new TextView(this),
				new TextView(this),
				new TextView(this),
		};
		((TextView)mTitles[0]).setTypeface(Typeface.create((String)null, 1));
		if(this.campName!=null)((TextView)mTitles[0]).setText(this.campName);else{
			((TextView)mTitles[0]).setText("Pulp Fiction Convention");
		}
		((TextView)mTitles[1]).setText("Details");
		((TextView)mTitles[2]).setText("Attachments");
		((TextView)mTitles[3]).setText("Members");
		for (int i = 0; i < 4; i++) {
			((TextView)mTitles[i]).setTextSize(20);
		}

		MyListAdapter l = new MyListAdapter(this,inflate,mDialogue, mTitles,0,260);

		setListAdapter(l);

		TextView t  = (TextView)mDialogue[0].findViewById(R.id.campdet_main_note1);
		TextView t2  = (TextView)mDialogue[0].findViewById(R.id.campdet_main_note2);
		StringBuilder st1= new StringBuilder();
		StringBuilder st2= new StringBuilder();	
		if (desc != null) {
			for (int i = 0; i < desc.length(); i++) {
				if (i > 50) {
					st2.append(desc.charAt(i));
				} else {
					st1.append(desc.charAt(i));
				}
			}
			t.setText(st1.toString());
			t2.setText(st2.toString());
		}

		TextView t3 = (TextView)mDialogue[1].findViewById(R.id.campdet_deta_creator_txt);
		t3.setText(creator);

		TextView t4 = (TextView)mDialogue[1].findViewById(R.id.campdet_deta_type_txt);
		if (isPublic.compareTo("0") == 0) {
			t4.setText("Private");
		} else {
			t4.setText("Public");
		}

		download = (Button)findViewById(R.id.foot_but2);
		upload = (Button)findViewById(R.id.foot_but3);
		refresh = (Button)findViewById(R.id.foot_but4);
	}

	public void onDestroy() {
		super.onDestroy();
		validThread = false;
		myBase.close();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) 
	{    
		refresh.setEnabled(false);
		download.setEnabled(false);
		upload.setEnabled(false);
		((MyListAdapter)getListAdapter()).toggle(position);
		if (position == 1) {
			window = 1;
			if (!validThread) new Thread(this).start();
		} else if (position == 2) {
			download.setEnabled(true);
			upload.setEnabled(true);
			refresh.setEnabled(true);
			String xml = ServerCom.getAttachments(CampDetails.this.id);

			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xml));
			Attachs factory = new Attachs();
			att = factory.fromXml(is);

			refresh.setOnClickListener(new OnClickListener() {
				public void onClick(View arg0) {
					String xml = ServerCom.getAttachments(CampDetails.this.id);
					InputSource is = new InputSource();
					is.setCharacterStream(new StringReader(xml));
					Attachs factory = new Attachs();
					att = factory.fromXml(is);
					int t = att.size();
					final View[] header = new View[t];
					final View[] body = new View[t];
					int i=0;
					for(Attachs a : att){
						// Log.d("LIST",a.fileName);
						if(a.getFileName()==null||a.getSize()==null)
							header[i]=inflate.inflate(R.layout.camp_det_atta_content, null);  //, null);
						body[i]=inflate.inflate(R.layout.camp_det_atta_content, null);  //, null);
						((TextView)body[i].findViewById(R.id.campdet_atta_header_title)).setText(a.getFileName());
						((TextView)body[i].findViewById(R.id.campdet_atta_header_progress)).setText(a.getSize()+" bytes");
						i++;
					}

					MyListAdapter l = new MyListAdapter(CampDetails.this,inflate,header, body,-1,135);
					attach.setAdapter(l);
					attach.setOnItemClickListener(new OnItemClickListener(){
						public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
						}});
				}
			});

			window = 2;
			// if(attach==null){
			int t = att.size();
			final View[] header = new View[t];
			final View[] body = new View[t];
			int i = 0;
			for (Attachs a : att) {
				header[i]=inflate.inflate(R.layout.camp_det_atta_content, null);  //, null);
				body[i]=inflate.inflate(R.layout.camp_det_atta_content, null);  //, null);
				((TextView)body[i].findViewById(R.id.campdet_atta_header_title)).setText(a.getFileName());
				((TextView)body[i].findViewById(R.id.campdet_atta_header_progress)).setText(a.getSize()+" bytes");
				i++;
			}

			attach = (ListView) this.findViewById(R.id.campdet_atta_list);

			upload.setOnClickListener(new OnClickListener(){
				public void onClick(View arg0) { }
			});

			upload.setOnClickListener(new OnClickListener() {
				public void onClick(View arg0) {
					ListView v = CampDetails.this.getListView();
					d = new Dialog(v.getContext());
					d.setContentView(R.layout.create_file);
					d.setTitle("Join Us! - Upload");
					Button b = (Button)d.findViewById(R.id.create_file_but);

					b.setOnClickListener(new OnClickListener(){
						public void onClick(View arg0) {
							Map <String, String> m = new HashMap<String, String>();
							m.put("filename", ((EditText)d.findViewById(R.id.create_file_name)).getText().toString());
							m.put("description", ((EditText)d.findViewById(R.id.create_file_desc)).getText().toString());
							//m.put("content", ((EditText)d.findViewById(R.id.create_file_content)).getText().toString());
							m.put("mimetype",  "(text/plain)");
							m.put("idCampaign", CampDetails.this.id);


							String resp = FileManagerDaemon.uploadFile(m, ((EditText) d.findViewById(R.id.create_file_content)).getText().toString());
							Log.d("upresp", resp);
							d.dismiss();

							/*int i=0;
							for(Attachs a : att) {
								header[i]=inflate.inflate(R.layout.camp_det_atta_content, null, null);
								body[i]=inflate.inflate(R.layout.camp_det_atta_content, null, null);
								((TextView)body[i].findViewById(R.id.campdet_atta_header_title)).setText(a.fileName);
								((TextView)body[i].findViewById(R.id.campdet_atta_header_progress)).setText(a.size+" bytes");
								i++;
							}*/
						}
					});
					d.show();
				}
			});

			download.setOnClickListener(new OnClickListener() {
				public void onClick(View arg0) {
					for (int i = 0; i < body.length; i++) {
						CheckBox cb = (CheckBox)body[i].findViewById(R.id.campdet_cb);
						if(cb.isChecked()){
							Map<String, String> m= new HashMap<String, String>();
							m.put("hash",att.elementAt(i).getHash());    		    				   
							m.put("campCreator",creator);
							m.put("size",att.elementAt(i).getSize());
							m.put("campName",campName);
							m.put("filename",att.elementAt(i).getFileName());
							m.put("type","");
							m.put("owner","gato astolfo");
							m.put("desc",att.elementAt(i).getDescri());
							m.put("idattach",att.elementAt(i).getIdAttach());

							Cursor c = myBase.query("fileContent", null, "idattach = '" + att.elementAt(i).getIdAttach() + "' AND id = '" + ServerCom.id + "'" , null, null, null, null);
							int cursorCount = c.getCount();
							c.close();
							if(cursorCount > 0) continue;

							FileManagerDaemon.queueDownload(m);
							// Log.d("cb",att.elementAt(i).fileName);
						}
					}
					Toast.makeText(CampDetails.this, "Downloading... go to the File Manager screen to see your downloads!", Toast.LENGTH_SHORT).show();
				}    		
			});

			MyListAdapter list = new MyListAdapter(this,inflate,header, body,-1,135);
			attach.setAdapter(list);

			attach.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				}});
			//}
			if (!validThread) new Thread(this).start();
		} else if (position == 3){
			if (members == null) {  
				View [] headers = new View[list.length];
				View [] body = new View[list.length];
				for (int i = 0; i < list.length; i++) {
					headers[i]=inflate.inflate(R.layout.camp_det_memb_cont, null);  //, null);
					body[i]=inflate.inflate(R.layout.camp_det_memb_body, null);  //, null);
					((TextView)headers[i].findViewById(R.id.campdet_memb_cont_title)).setText(list[i]);
				}

				members = (ListView)this.findViewById(R.id.campdet_memb_list);

				MyListAdapter list = new MyListAdapter(this, inflate, body, headers, -1,75);
				members.setAdapter(list);
			}
		} else {
			TextView t = (TextView)this.findViewById(R.id.campdet_main_note1);
			if (desc != null) t.setText(desc);
		}
	}

	int window = 0;

	public void run() {
		validThread = true;
		TextView v = null;
		while (validThread) {
			if (window == 1) {
				long c, i = SystemClock.elapsedRealtime();

				while (validThread && window == 1) {
					i--;
					v = (TextView)this.findViewById(R.id.campdet_deta_expires_txt);
					SystemClock.sleep(1000);
					if (v == null) continue;
					c =  SystemClock.elapsedRealtime();
					final Calendar cal = Calendar.getInstance();

					String s = cal.get(Calendar.HOUR_OF_DAY) + " "
					+ cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.MONTH);
					Log.d("actual", s);

					c = (CampDetails.this.millis / 1000) - (cal.getTimeInMillis() / 1000);
					Log.d("result",c+"");
				}
			}
		}
	}
}

class Download extends CampDetails implements Runnable {
	TextView t;
	ProgressBar p;
	int progress;

	Download(TextView t, ProgressBar pb, int p){
		this.t=t;
		progress=p;
		this.p=pb;
	}

	public void run() {
		if(progress<100){
			t.setText(progress+"%");
		}else{
			t.setText("done!");
			p.setVisibility(View.INVISIBLE);
		}
	}
}

class Clock extends CampDetails implements Runnable {
	TextView t;
	long i;

	Clock(TextView t, long i) {
		this.t = t;
		this.i = i;
	}

	public void run() {
		String s1 = "", s2 = "";
		if(i<=0){
			t.setText("Expired!");
			return;
		}
		if(i<60){
			if(i==1){s1="";}else{s1="s";}
			t.setText(i+" second"+s1 +".");
		}else if(i<60*60){
			if((i/60)==1){s1="";}else{s1="s";}
			if((i%60)==1){s2="";}else{s2="s";}
			t.setText(i/60+" minute"+s1+ " and "+i%60 +" second"+s2+".");
		}else if(i<(60*60*24)){
			if(i/(60*60)==1){s1="";}else{s1="s";}
			if((i%(60*60))/60==1){s2="";}else{s2="s";}
			t.setText(i/(60*60)+" hour"+s1+" and "+(i%(60*60))/60 +" minute"+s2+".");
		}else if(i<(60*60*24*365)){
			if(i/(60*60*24)==1){s1="";}else{s1="s";}
			if((i%(60*60*24))/(60*60)==1){s2="";}else{s2="s";}
			t.setText(i/(60*60*24)+" day"+s1+" and "+(i%(60*60*24))/(60*60) +" hour"+s2+".");
		}else{
			if(i/(60*60*24*365)==1){s1="";}else{s1="s";}
			if((i%(60*60*24*365))/(60*60*24)==1){s2="";}else{s2="s";}
			t.setText(i/(60*60*24*365)+" year"+s1+" and "+(i%(60*60*24))/(60*60*24) +" day"+s2+".");			
		}
	}
}
